import fs from 'fs';
import lodash from 'lodash';

const Plugin_Path = `${process.cwd()}/plugins/bilibili-plugin`;
const README_path = `${Plugin_Path}/README.md`;
const CHANGELOG_path = `${Plugin_Path}/CHANGELOG.md`;
let yunzai_ver = '';

try {
  const packageJson = JSON.parse(fs.readFileSync(`${process.cwd()}/package.json`, 'utf8'));
  yunzai_ver = packageJson.version;
} catch (err) {
  console.error('读取 package.json 失败:', err);
}

let changelogs = [];
let currentVersion = '';
let versionCount = 10;

const getLine = (line) => {
  return line.replace(/(^\s*\*|\r)/g, '')
             .replace(/\s*`([^`]+)`/g, '<span class="cmd">$1</span>')
             .replace(/\*\*(.+?)\*\*/g, '<span class="strong">$1</span>')
             .replace(/ⁿᵉʷ/g, '<span class="new"></span>');
};

try {
  if (fs.existsSync(CHANGELOG_path)) {
    const logs = fs.readFileSync(CHANGELOG_path, 'utf8').replace(/\t/g, '   ').split('\n');
    let temp = {};
    let lastLine = {};

    lodash.forEach(logs, (line) => {
      if (versionCount < 1) return false;

      const versionRet = /^#\s*([0-9a-zA-Z\\.~\s]+?)\s*$/.exec(line.trim());
      if (versionRet && versionRet[1]) {
        const v = versionRet[1].trim();
        if (!currentVersion) {
          currentVersion = v;
        } else {
          changelogs.push(temp);
          versionCount--;
          if (/0\s*$/.test(v)) versionCount--;
        }
        temp = {
          version: v,
          logs: []
        };
      } else if (!line.trim()) {
        return;
      } else if (/^\*/.test(line)) {
        lastLine = {
          title: getLine(line),
          logs: []
        };
        if (!temp.logs) {
          temp = {
            version: '',
            logs: []
          };
        }
        temp.logs.push(lastLine);
      } else if (/^\s{2,}\*/.test(line)) {
        lastLine.logs.push(getLine(line));
      }
    });
  }
} catch (e) {
  console.error('处理 CHANGELOG 失败:', e);
}

try {
  if (fs.existsSync(README_path)) {
    const README = fs.readFileSync(README_path, 'utf8');
    const reg = /版本：(.*)/.exec(README);
    if (reg) {
      currentVersion = reg[1];
    }
  }
} catch (err) {
  console.error('读取 README.md 失败:', err);
}

const Version = {
  get ver() {
    return currentVersion;
  },
  get yunzai() {
    return yunzai_ver;
  },
  get logs() {
    return changelogs;
  }
};

export default Version;
